package com.lagou.service.impl;

import com.lagou.feign.EmailFeignClient;
import com.lagou.mapper.CodeMapper;
import com.lagou.pojo.User;
import com.lagou.service.CodeService;
import com.lagou.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    @Reference
    private MailService mailService;

    @Autowired
    private CodeMapper codeMapper;


    @Override
    public boolean createCode(String email) {
        //获得六位随机码
        boolean flag = false;
        String code = "";
        try {
            code =String.format("%06d", new Random().nextInt(1000000));

            User user = new User();
            user.setEmail(email);
            user.setVerificationCode(code);
            //先存入数据库
            codeMapper.saveCode(user);
            // 调用dubbo发送
            mailService.sendVerificationCode(user);
        }catch (Exception e){
            log.error("error", e);
            return false;
        }

        log.info("验证码创建成功" + code);
        return flag;
    }

    @Override
    public int codeValidate(String email, String code) throws ParseException {

        User user = new User();
        user.setEmail(email);
        user.setVerificationCode(code);

        String codetime = codeMapper.queryCodetime(user);

        if(StringUtils.isEmpty(codetime)){
            return 1;
        }

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = ft.parse(codetime);

        long secend = new Date().getTime() - date.getTime();

        if(secend > 60000){
            return 2;
        }

        return 0;
    }
}
